//
// Created by sgyt on 2020/3/16.
// 消息队列接收端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

struct msg_st
{
    long int msg_type;
    char text[BUFSIZ];
};

int main(int argc,char *argv[])
{
    int msgid = -1;
    struct msg_st data;
    long int msgtype = 0;

    //建立消息队列
    msgid = msgget((key_t)1234,0666|IPC_CREAT);
    if(msgid < 0)
    {
        perror("msgget is error\n");
        exit(EXIT_FAILURE);
    }

    //从队列中获取消息，知道遇到end消息为止
    while(1)
    {
        if(msgrcv(msgid,(void *)&data,BUFSIZ,msgtype,0) == -1)
        {
            perror("msgrcv is error\n");
            exit(EXIT_FAILURE);
        }

        printf("Your wrote:%s\n",data.text);

        //遇到end 结束
        if(strncmp(data.text,"end",3))
        {
            break;
        }
    }

    //删除消息队列
    if(msgctl(msgid,IPC_RMID,0))
    {
        perror("msg close is error\n");
        exit(EXIT_FAILURE);
    }
    return EXIT_SUCCESS;
}

